package com.loren.oauth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loren.oauth.data.resp.ErrorResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@AllArgsConstructor
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

	private final ObjectMapper objectMapper;

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

		response.setStatus(HttpStatus.UNAUTHORIZED.value());

		response.setContentType("application/json;charset=utf-8");

		ErrorResponse errorResponse = new ErrorResponse(ErrorResponse.NEED_AUTH_CODE, "unauthorized access");

		response.getWriter().write(this.objectMapper.writeValueAsString(errorResponse));
	}
}
